import { Configuration, App, Inject } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { join } from 'path';
import { ReportMiddleware } from './middleware/report.middleware';
import * as dotenv from 'dotenv';
import DecoratorService from './service/decorator.service';
import { readdirSync } from 'fs';
dotenv.config();
dotenv.config({ path: join(__dirname, '../.env.' + process.env.NODE_ENV) });
import config from './config/config';
@Configuration({
  imports: [
    koa,
    validate,
    {
      component: info,
      enabledEnvironment: ['local'],
    },
  ],
  importConfigs: [{ default: config }],
})
export class ContainerLifeCycle {
  @App()
  app: koa.Application;

  @Inject()
  decoratorService: DecoratorService;

  async onInit(options) {}

  async onConfigLoad(options) {
    const config = {};
    const files = await readdirSync(join(__dirname, './config'));
    files.forEach(file => {
      const [name] = file.split('.');
      const value = require('./config/' + file).default;
      if (name !== 'config') {
        config[name] = value;
      }
    });
    await this.databaseConfig(config);
    return config;
  }

  async onReady() {
    // add middleware
    this.app.useMiddleware([ReportMiddleware]);
    this.decoratorService.register();
  }

  async databaseConfig(config) {
    const databaseConfig = config['database'];
    const drivers = databaseConfig['drivers'];
    const driver = databaseConfig['default'];
    const driverConfig = drivers[driver];
    config[driverConfig['orm']] = await this[driverConfig['orm']](driverConfig);
    return config;
  }

  async typeorm(config) {
    const entities = [];
    if (config['models'] !== undefined && config['models'] != null) {
      const models = await readdirSync(join(__dirname, config['models']));

      models.forEach(file => {
        const value = require(config['models'] + file).default;
        entities.push(value);
      });
    }

    return {
      dataSource: {
        default: {
          /**
           * 单数据库实例
           */
          type: config['driver'],
          host: config['host'],
          port: config['port'],
          username: config['username'],
          password: config['password'],
          database: config['database'],
          synchronize: false, // 如果第一次使用，不存在表，有同步的需求可以写 true，注意会丢数据
          logging: false,

          // 配置实体模型
          entities: entities,
        },
      },
    };
  }

  cacheConfig(config) {}
}
